<?php

class Controller_Admin_Gender extends Controller_Admin
{
	public function before()
	{
		parent::before();
		// set sidebar
		$this->data['sidebar'] = View::forge('admin/items/sidebar');
	}

	public function action_index()
	{	
		$list = Lib\ZList::forge('genders', array(
			'url' => 'admin/gender/index',
			'page' => Input::get('p'),
			'limit' => 18
		));
		if(Input::get('s') != '')
		{
			$list->fulltext(array(
				array('name', Input::get('s'))
			));
			
			$list->set_vars(array('s' => Input::get('s')));
		}
		$list->order_by('name');
		$list = $list->get();
		
		$this->set('zlist', $list);
		$this->set('pagination', $list->pagination);
	}

	public function action_add()
	{
		if(Input::method() == 'POST')
		{
			$val = Lib\Validate::forge();
			$val->add_fields(array(
				'name' => array(
					'label' => 'Title',
					'validate' => 'required'
				)
			));

			if(!$val->run())
			{
				Lib\Response::json(array(
					'alert' => $val->get_errors()
				), true);
			}

			$post = Model_gender::forge($val->validated());
			$post->save();

			Lib\Response::json(array(
				'notice' => 'Added successfully',
				'redirect' => Uri::create('admin/gender')
			), true);
		}
	}

	public function action_edit($id = 0)
	{
		if(Input::method() == 'POST')
		{
			$val = Lib\Validate::forge();
			$val->add_fields(array(
				'id' => array(
					'validate' => 'required',
					'messages' => array(
						'required' => 'gender does not exists'
					)
				),
				'name' => array(
					'label' => 'Title',
					'validate' => 'required|trim'
				)
			));

			if(!$val->run())
			{
				Lib\Response::json(array(
					'alert' => $val->get_errors()
				), true);
			}

			$data = $val->validated();
			$post = Model_gender::find($data['id']);

			if(!$post)
			{
				Lib\Response::json(array(
					'alert' => 'gender does not exists',
					'redirect' => Uri::create('admin/gender')
				), true);
			}

			$post->name = $data['name'];
			$post->save();

			Lib\Response::json(array(
				'notice' => 'Updated successfully',
				'redirect' => Uri::create('admin/gender')
			), true);
		}

		$id = (int) $id;
		$post = Model_gender::find($id);

		if(!$post || !$id)
		{
			Lib\Response::json(array(
				'alert' => 'Not exists',
				'redirect' => Uri::create('admin/gender')
			), true);
		}

		$this->set('post', $post);
	}

	public function action_delete()
	{
		if(Input::method() == 'POST')
		{
			$id = (array) Input::post('id');
			if(!$id)
			{
				Lib\Response::json(array(
					'alert' => 'Not exists',
					'redirect' => Uri::create('admin/gender')
				), true);
			}

			DB::delete('genders')->where('id', 'in', $id)->execute();
			
			Lib\Response::json(array(
				'notice' => 'Deleted successfully',
				'redirect' => Uri::create('admin/gender')
			), true);
		}
	}
}